<!DOCTYPE html>
<html>
<title>Media Controls: Test controls layout correctly in different small sizes.</title>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="../../resources/run-after-layout-and-paint.js"></script>
<script src="../media-controls.js"></script>
<video controls></video>
<script>
async_test(t => {
  const video = document.querySelector('video');
  video.src = '../content/test.ogv';

  video.onloadedmetadata = t.step_func(() => {
    // We are testing the changing of sizes instead of single test cases
    // because the layout flilkering issue typically happen when changing
    // from small size to big size.
    const testCases = [ 400, 100, 180, 200, 100, 200, 100, 250, 100, 300 ];
    const buttonPanel = buttonPanelElement(video);
    const overflowBtn = overflowButton(video);

    runTestCase(0);

    function runTestCase(index) {
      let test = testCases[index];
      video.width = test;
      runAfterLayoutAndPaint(t.step_func(() => {
        expectLayoutCorrectly();

        assert_not_equals(getComputedStyle(overflowBtn), 'none',
                          'Overflow button should always be visible');

        let nextIndex = index + 1;
        if (nextIndex === testCases.length) {
          testLayoutWhilePlaying();
          return;
        }
        runTestCase(nextIndex);
      }));
    }

    function testLayoutWhilePlaying() {
      video.width = 400;

      // Start playing video and wait for controls to hide
      video.addEventListener('playing', t.step_func(() => {
        runAfterHideMediaControlsTimerFired(t.step_func(() => {
          assert_false(isControlsPanelVisible(video), 'controls should not be shown');

          // Change width to 80 and check layout
          video.width = 80;
          runAfterLayoutAndPaint(t.step_func(() => {

            // Hover to show the controls
            hoverOverControl(video, t.step_func_done(() => {
              expectLayoutCorrectly();
            }));
          }));
        }), video);
      }), {once: true});
      video.play();
    }

    function expectLayoutCorrectly() {
      let totalWidth = 0;
      let children = buttonPanel.children;
      for (let i = 0; i < children.length; i++) {
        let child = children[i];
        if (getComputedStyle(child).display != 'none')
          totalWidth += child.getBoundingClientRect().width;
      }

      assert_true(buttonPanel.getBoundingClientRect().width > 0, 'control panel width should always be positive when we testing');
      assert_true(totalWidth <= buttonPanel.getBoundingClientRect().width,
                  'All element should fit in button panel');
    }
  });
});
</script>
</html>
